﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Components_SaleOrder : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["SaleOrderID"] = null;
            Session.Remove("SaleOrderID");
           // loadDataTest();
            LoadForm();
            loadData();
           // Session["listPromotion"] = null;
           // Session.Remove("listPromotion");
        }
    }

    private void LoadForm()
    {
        try
        {
            Utils.loadLocation(cboProvince, 0, 1, 1);
            Utils.loadLocation(cboDistrict, int.Parse(cboProvince.SelectedValue), 1, 2);
            dtpReceiptDate.SelectedDate = DateTime.Now.Date;
            dtpReceiptDate.MinDate = DateTime.Now;
        }catch(Exception ex){
            ControlUtil.LogError("SaleOrder-LoadForm:" + ex.Message);
        }
    }

    private bool checkPromotion()
    {
        bool result = true;
        try
        {
            //Check thu co qua KM khong
            foreach (GridViewRow row in gvPromotion.Rows)
            {
                RadNumericTextBox TxtQuantitySelect = (RadNumericTextBox)row.FindControl("txtQuantitySelect");
                int QuantitySelect = int.Parse(TxtQuantitySelect.Text);

                int PromotionRemainQty = int.Parse(row.Cells[8].Text);
               // if (PromotionRemainQty > QuantitySelect)
                if (PromotionRemainQty > 0)
                {
                    return result = false;
                }

            }
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-checkPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
            return result = false;
        }
        return result;
    }

    protected void btnOrder_Click(object sender, EventArgs e)
    {
        
        SaleOrderRequest saleOrder = createSaleOrderRequestObj();
        try
        {
            if (Page.IsValid)
            {

                //int CustomerID = 0;
                //if (string.IsNullOrEmpty(this.hidCusID.Value))
               // {
                int CustomerID  = CreateCustomer();
                //}

                saleOrder.CustomerID = CustomerID;
                decimal? DiscountAmount = CalcDiscount(DecimalOrNull(DivAccumulateAmount.InnerText), CustomerID);
                saleOrder.DiscountAmount = double.Parse(DiscountAmount.ToString());
                saleOrder.Total = saleOrder.Amount - saleOrder.DiscountAmount;
                db.Insert<SaleOrderRequest>(saleOrder);
                db.SubmitChanges();

                //decimal? sum = 0;
                //int totalWeight = 0;
                List<SaleOrderRequestDetail> listDetail = new List<SaleOrderRequestDetail>();
                foreach (GridViewRow row in gvProduct.Rows)
                {

                    Label PriceLabel = (Label)row.FindControl("lblPrice");
                    Label AmountLabel = (Label)row.FindControl("lblAmount");
                    RadNumericTextBox txtQuantity = (RadNumericTextBox)row.FindControl("txtQuantity");
                    if (double.Parse(txtQuantity.Text.Replace(",", "")) <= 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập trọng lượng lớn hơn 0");
                        return;
                    }
                    /*
                    sum = sum + DecimalOrNull(AmountLabel.Text.Replace(",", ""));
                    totalWeight = totalWeight + int.Parse(txtQuantity.Text.Replace(",", ""));
                     */
                    SaleOrderRequestDetail soDetail = new SaleOrderRequestDetail();
                    soDetail.SaleOrderRequestID = saleOrder.ID;
                    soDetail.ProductID = int.Parse(row.Cells[4].Text);
                    soDetail.Price = double.Parse(PriceLabel.Text);
                    soDetail.Weight = double.Parse(txtQuantity.Text.Replace(",", ""));
                    soDetail.Amount = soDetail.Price * soDetail.Weight;
                    soDetail.CreatedBy = "Web";
                    soDetail.LastUpdatedBy = "Web";
                    soDetail.CreatedDateTime = DateTime.Now;
                    soDetail.LastUpdatedDateTime = DateTime.Now;
                    soDetail.Status = 'N';
                    listDetail.Add(soDetail);
                }
                db.Insert<SaleOrderRequestDetail>(listDetail);
                //JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");
                //Insert KM 
                List<SaleOrderRequestPromotion> listPro = InsertPromotion(saleOrder.ID);

                db.SubmitChanges();
                Session["ShoppingCart"] = null;
                Session.Remove("ShoppingCart");
                Session["SaleOrderID"] = saleOrder.ID;

                if (checkPromotion() == false)//Neu chua chon KM đủ, se den trang KM
                {
                   // Session["listPromotion"] = listPro;
                    Response.Redirect("~/san-pham-qua-tang/" + saleOrder.ID, false);
                }
                else
                {
                    Response.Redirect("~/dat-hang-thanh-cong/" + saleOrder.ID, false);
                }
            }
        }
        catch (Exception ex)
        {
            // db.Delete<SaleOrderRequest>(saleOrder);
            //db.SubmitChanges();
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Luu don dat hang");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
            return;
        }
    }

    private List<SaleOrderRequestPromotion> InsertPromotion(int SaleOrderRequestID)
    {
        List<SaleOrderRequestPromotion> listPro = new List<SaleOrderRequestPromotion>();
        try
        {
            foreach (GridViewRow row in gvPromotion.Rows)
            {
                SaleOrderRequestPromotion saleOrderPromotion = new SaleOrderRequestPromotion();

                int ProductID = int.Parse(row.Cells[2].Text);
                int PromotionDetailID = int.Parse(row.Cells[4].Text);
                int PromotionID = int.Parse(row.Cells[3].Text);
                RadNumericTextBox QuantitySelect = (RadNumericTextBox)row.FindControl("txtQuantitySelect");
                int PromotionRemainQty = int.Parse(row.Cells[8].Text);
                int Weight = int.Parse(row.Cells[5].Text);

                saleOrderPromotion.ProductID = ProductID;
                saleOrderPromotion.SaleOrderRequestID = SaleOrderRequestID;
                saleOrderPromotion.QuantitySelect = int.Parse(QuantitySelect.Text);
                saleOrderPromotion.PromotionID = PromotionID;
                saleOrderPromotion.PromotionDetailID = PromotionDetailID;
                saleOrderPromotion.PromotionRemainQty = PromotionRemainQty;
                saleOrderPromotion.Weight = Weight;
                saleOrderPromotion.CreatedBy = "Web";
                saleOrderPromotion.LastUpdatedBy = "Web";
                saleOrderPromotion.CreatedDateTime = DateTime.Now;
                saleOrderPromotion.LastUpdatedDateTime = DateTime.Now;
                saleOrderPromotion.Status = 'N';//Moi luu
                listPro.Add(saleOrderPromotion);
            }
            db.Insert<SaleOrderRequestPromotion>(listPro);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-InsertPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return listPro;
    }
    private SaleOrderRequest createSaleOrderRequestObj()
    {

        SaleOrderRequest saleOrder = new SaleOrderRequest();
        try
        {
            String CustomerName = Utils.KillChars(this.txtFullName.Text.Trim());
            String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
            String Address = Utils.KillChars(this.txtAddress.Text.Trim());
            int DistrictID = Convert.ToInt32(this.cboDistrict.SelectedValue == "" ? "0" : this.cboDistrict.SelectedValue);
            int ProvinceID = Convert.ToInt32(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
            String DistrictName = cboDistrict.SelectedItem.Text;
            String ProvinceName = cboProvince.SelectedItem.Text;
            //  var CustomerID = (from c in db.Customers where c.PhoneNumber == this.txtPhoneNumber.Text.Trim() && c.Status=='A' select c.ID).FirstOrDefault();
            var ShopID = db.ShopLocations.FirstOrDefault(sl => sl.DistrictID == DistrictID && sl.ProvinceID == ProvinceID);

            //Lay ma sau cung
            int lenZero = 10;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
            var CodeMax = db.SaleOrderRequests.Max(d => d.OrderNumber);
            int MaxOrderNumber = (CodeMax == null ? 0 : Convert.ToInt32(CodeMax)) + 1;
            String LastCode = ("0000000000" + MaxOrderNumber).ToString();
            String Code = "DD" + LastCode.Substring(LastCode.Length - lenZero);
            //End
            saleOrder.OrderNumber = MaxOrderNumber;
            saleOrder.SaleOrderRequestCode = Code;
            // saleOrder.CustomerID = CustomerID;
            saleOrder.SaleOderType = "W";
            // saleOrder.DiscountAmount = double.Parse(DivDiscountAmount.InnerText);
            saleOrder.Amount = double.Parse(DivAccumulateAmount.InnerText);
            //saleOrder.Total = double.Parse(DivSumPayment.InnerText);
            saleOrder.ShopID = (ShopID != null ? IntOrNull(ShopID.ID) : 0);
            saleOrder.TotalWeight = Convert.ToInt32(sumWeight.InnerText);
            //thong tin giao hang
            saleOrder.PersonReceipt = txtFullName.Text.Trim();
            saleOrder.PhoneNumberReceipt = txtPhoneNumber.Text.Trim();
            saleOrder.AddressReceipt = txtAddress.Text.Trim() +", "+DistrictName+", "+ProvinceName;
            saleOrder.DateTimeReceipt = dtpReceiptDate.SelectedDate;

            saleOrder.CreatedBy = "Web";
            saleOrder.LastUpdatedBy = "Web";
            saleOrder.CreatedDateTime = DateTime.Now;
            saleOrder.LastUpdatedDateTime = DateTime.Now;
            saleOrder.Status = 'N';
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-createSaleOrderRequestObj");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return saleOrder;
    }

    private int CreateCustomer()
    {
        Customer customer = createCustomerObj();
        try
        {
            //check neu trung thi update
            var checkCus = (from cus in db.Customers
                         where cus.PhoneNumber == customer.PhoneNumber
                         select cus).FirstOrDefault();
            if (checkCus != null)
            {
                db.Update<Customer>(customer);
            }
            else
            {
                //Lay ma sau cung
                int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var customerCodeMax = db.Customers.Max(d => d.OrderNumber);
                int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
                String LastCode = ("000000" + MaxOrderNumber).ToString();
                String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
                //End
                 customer.OrderNumber = MaxOrderNumber;
                 customer.CustomerCode = CustomerCode;
                 customer.Status = 'A';
                 db.Insert<Customer>(customer);
            }
            db.SubmitChanges();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-CreateCustomer");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return customer.ID;
    }

    private Customer createCustomerObj()
    {
        String CustomerName = Utils.KillChars(this.txtFullName.Text.Trim());
        String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
        String Address = Utils.KillChars(this.txtAddress.Text.Trim());
        int DistrictID = Convert.ToInt32(this.cboDistrict.SelectedValue == "" ? "0" : this.cboDistrict.SelectedValue);
        int ProvinceID = Convert.ToInt32(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);

        Customer customer = new Customer();

        var checkCus = (from cus in db.Customers
                        where cus.PhoneNumber.Trim() == CustomerPhone.Trim()
                        select cus).FirstOrDefault();
        if (checkCus != null)
        {
            customer = checkCus;
        }
        customer.CustomerName = CustomerName;
        customer.PhoneNumber = CustomerPhone.Trim();
        customer.Email = "";
        customer.Address = Address;
        customer.DistrictID = DistrictID;
        customer.ProvinceID = ProvinceID;
        customer.AccumulateAmount = 0;
        customer.ConvertedAmount = 0;
        customer.RemainAmount = 0;
        customer.CreatedBy = "Web";
        customer.CreatedDateTime = DateTime.Now;
        customer.LastUpdatedBy = "Web";
        customer.LastUpdatedDateTime = DateTime.Now;
        customer.Status = 'A';
       
        return customer;
    }
    protected void btnCont_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/san-pham", false);
    }
    protected void btnDeleteCard_Click(object sender, EventArgs e)
    {
        Session["ShoppingCart"] = null;
        Session.Remove("ShoppingCart");
        Response.Redirect("~/san-pham", false);
    }
    protected void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        string provinceID = cboProvince.SelectedValue;
        Utils.loadLocation(cboDistrict, int.Parse(provinceID), 0,0);
    }

    private void loadData()
    {
        try
        {
            DataTable dt = new DataTable();

            if (Session["ShoppingCart"] != null)
            {
                dt = (DataTable)Session["ShoppingCart"];
                gvProduct.DataSource = dt;
                gvProduct.DataBind();

               // int totalWeight = Convert.ToInt32(dt.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"])));
                int totalWeight = Convert.ToInt32(dt.AsEnumerable().Where(a => a.Field<Int32>("IsPromotion") == 1).Sum(dr => IntOrNull(dr["Weight"])));
                sumWeight.InnerText = totalWeight.ToString();
                CalSum(dt);
                DataTable dtPro = loadPromotionPromotion(totalWeight, 0);
                bindingPromotion(dtPro);
            }
            else
            {
                Response.Redirect("~/san-pham", false);
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadData");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
       
    }

    private void CalSum(DataTable dt)
    {
        //decimal vat = decimal.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);
        var sum = dt.AsEnumerable().Sum(dr => DecimalOrNull(dr["Amount"]));
        // double discount = Convert.ToDouble(CalcDiscount(sum));//tinh giam gia
        CalsumHelp(sum, 0, 0);
    }

    private void CalsumHelp(decimal? sum, decimal vat, double discount)
    {

        double Payment = Convert.ToDouble(sum * (vat + 1)) - discount;
        sumTotal.InnerText = "Tổng: " + String.Format("{0:#,#.##}", sum) + " VNĐ";

        if (vat != 0)
        {
            sumTotalTax.Visible = true;
            sumTotalTax.InnerText = "Sau thuế: " + String.Format("{0:#,#.##}", sum * (vat + 1)) + " VNĐ";
        }
        else
        {
            sumTotalTax.Visible = false;
        }
        //sumPayment.InnerText = "Thanh toán: " + String.Format("{0:#,#.##}", Payment) + " VNĐ";

        DivSumPayment.InnerText = Payment.ToString();//So tien phai thanh toan
        DivAccumulateAmount.InnerText = sum.ToString();//Tong tien truoc thue
    }

    private decimal? CalcDiscount(decimal? total,int CusID)
    {
        decimal? Discount = 0;
        var cus = (from c in db.Customers
                   where c.ID == CusID
                   select c).FirstOrDefault();
        if (cus != null)
        {
            decimal? TotalRemainAmount = DecimalOrNull(cus.RemainAmount) + DecimalOrNull(total);

            //Lay so tien duoc huong KM
            DateTime date = DateTime.Now.Date;
            var promotion = (from p in db.Promotions
                             join pd in db.PromotionDetails on p.ID equals pd.PromotionID
                             where p.Status == 'A' && pd.Status == 'A' && p.PromotionType == "M"
                             && date >= p.StartDate && date <= p.EndDate
                             orderby p.LastUpdatedDateTime descending
                             select new
                             {
                                 Amount = pd.Amount,
                                 DiscountAmount = pd.DiscountAmount,
                                 PromotionID = pd.PromotionID,
                                 PromotionDetailID = pd.ID,
                             }
                                ).First();

            int? number = IntOrNull(TotalRemainAmount < DecimalOrNull(promotion.Amount) ? 0 : (IntOrNull(TotalRemainAmount) / IntOrNull(promotion.Amount)));
            Discount = number * DecimalOrNull(promotion.DiscountAmount);//giam gia
            DivDiscountAmount.InnerText = Discount.ToString();//Giam gia
            DivConvertedAmount.InnerText = (number * promotion.Amount).ToString(); // tong tien da quy doi
            DivDiscountPromotionDetailID.InnerText = promotion.PromotionDetailID.ToString();
            DivDiscountPromotionID.InnerText = promotion.PromotionID.ToString();
        }
        return Discount;
    }
  
    private DataTable loadPromotionPromotion(int totalWeight, int totalWeightSelected)
    {

        DataTable dtPromotion = createDataTablPromotion();
        try
        {
            int totalWeightRemain = totalWeight - totalWeightSelected;

            if (totalWeight > 0)
            {

                //Lay danh sach sp KM
                DataTable dtProductPromotion = getListProductPromotion();
                int PromotionQuantity = 0;
                foreach (DataRow detail in dtProductPromotion.Rows)
                {
                    PromotionQuantity = totalWeightRemain / Convert.ToInt32(detail["Weight"]);
                    // if (PromotionQuantity > 0)
                    //{
                    DataRow drNew = dtPromotion.NewRow();
                    drNew["ProductID"] = detail["ProductID"];
                    drNew["ProductCode"] = detail["ProductCode"];
                    drNew["ProductName"] = detail["ProductName"];
                    drNew["PromotionDetailID"] = detail["PromotionDetailID"];
                    drNew["Weight"] = detail["Weight"];
                    drNew["PromotionID"] = detail["PromotionID"];
                    drNew["Image"] = detail["Image"];
                    drNew["PromotionQuantity"] = PromotionQuantity;
                    drNew["PromotionQuantitySelect"] = 0;
                    dtPromotion.Rows.Add(drNew);
                    // }
                }
            }
            ViewState["dtPromotion"] = dtPromotion;
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadPromotionPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return dtPromotion;
    }

    private DataTable getListProductPromotion()
    {
        DataTable dt = new DataTable();
        try
        {
            if (CacheUtil.GetCache("ListProductPromotion") == null)
            {
                DateTime date = DateTime.Now.Date;
                var listPromotion = (from p in db.Promotions
                                     join pd in db.PromotionDetails on p.ID equals pd.PromotionID
                                     join pro in db.Products on pd.ProductID equals pro.ID
                                     where p.Status == 'A' && pd.Status == 'A' && p.PromotionType == "K"
                                     && pro.Status == 'A' && pro.ProductType == "P"
                                     && date >= p.StartDate && date <= p.EndDate
                                     select new
                                     {
                                         ProductID = pd.ProductID,
                                         PromotionID = pd.PromotionID,
                                         PromotionDetailID = pd.ID,
                                         ProductCode = pro.ProductCode,
                                         ProductName = pro.ProductName,
                                         Weight = pd.Weight,
                                         Image = pro.ImagePath
                                     }
                                    ).ToList();
                dt = listPromotion.ToDataTable();
                CacheUtil.InsertCache("ListProductPromotion", dt);
            }
            else
            {
                dt = (DataTable)CacheUtil.GetCache("ListProductPromotion");
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadPromotionPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return dt;
    }
    private DataTable createDataTablPromotion()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ProductID");
        dt.Columns.Add("ProductCode");
        dt.Columns.Add("ProductName");
        dt.Columns.Add("PromotionDetailID");
        dt.Columns.Add("Weight");
        dt.Columns.Add("PromotionID");
        dt.Columns.Add("Image");
        dt.Columns.Add("PromotionQuantity");
        dt.Columns.Add("PromotionQuantitySelect");
        return dt;
    }
    private void bindingPromotion(DataTable dtPro)
    {
        if (dtPro.Rows.Count > 5)
        {
            gvPromotion.Height = 150;
            // gvPromotion.ClientSettings.Scrolling.AllowScroll = true;
        }
        //gvPromotion.ClientSettings.Scrolling.UseStaticHeaders = true;
        gvPromotion.DataSource = dtPro;
        gvPromotion.DataBind();
    }

    private DataTable createDataTableProduct()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ProductName");
        dt.Columns.Add("ProductID");
        dt.Columns.Add("Price");
        dt.Columns.Add("Weight");
        dt.Columns.Add("Amount");
        return dt;
    }

    protected void grvProduct_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "cmdDelete")
        {
            string ProductID = e.CommandArgument.ToString();
            deleteCart(ProductID);
        }
    }

    private void deleteCart(string ProductID)
    {

        if (Session["ShoppingCart"] != null)
        {
            DataTable dt = (DataTable)Session["ShoppingCart"];
            DataRow[] rowArr = dt.Select("ProductID='" + ProductID + "'");
            foreach (DataRow r in rowArr)
            {
                r.Delete();
            }
            if (dt.Rows.Count > 0)
            {
                Session["ShoppingCart"] = dt;
            }
            else
            {
                Session["ShoppingCart"] = null;
                Session.Remove("ShoppingCart");
                //Response.Redirect("~/san-pham", true);
            }
            loadData();
        }
    }

    /*
    protected void txtPhoneNumber_TextChanged(object sender, EventArgs e)
    {
        try
        {
            string Input = this.txtPhoneNumber.Text.Trim().ToLower();
            if (Input != "")
            {
                var cus = (from c in db.Customers
                           where c.PhoneNumber == Input//c.PhoneNumber.IndexOf(Input) != -1
                           select c).FirstOrDefault();
                if (cus != null)
                {

                    this.txtPhoneNumber.Text = cus.PhoneNumber;
                    this.txtAddress.Text = cus.Address;
                    this.txtFullName.Text = cus.CustomerName;
                    this.cboDistrict.SelectedValue = cus.DistrictID.ToString();
                    this.cboProvince.SelectedValue = cus.ProvinceID.ToString();
                    hidCusID.Value = cus.ID.ToString();
                }
                else
                {
                    this.txtAddress.Text = "";
                    this.txtFullName.Text = "";
                    Utils.loadLocation(cboProvince, 0, 0, 1);
                    Utils.loadLocation(cboDistrict, int.Parse(cboProvince.SelectedValue), 0, 2);
                    hidCusID.Value ="";
                }
            }
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-txtPhoneNumber_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
       // this.txtAddress.Focus();
    }
     */ 
    private decimal? DecimalOrNull(object val)
    {
        try
        {
            return Convert.ToDecimal(val);
        }
        catch
        {
            return null;
        }
    }

    private int? IntOrNull(object val)
    {
        try
        {
            return Convert.ToInt32(val);
        }
        catch
        {
            return null;
        }
    }
    /*
    //nho xoa
    private void loadDataTest()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ProductID");
        dt.Columns.Add("ProductName");
        dt.Columns.Add("ProductCode");
        dt.Columns.Add("Price");
        dt.Columns.Add("Weight");
        dt.Columns.Add("Amount");
        //du lieu test
        DataRow row1 = dt.NewRow();
        row1["ProductName"] = "Gạo thơm";
        row1["ProductID"] = "2";
        row1["Price"] = "13000";
        row1["Weight"] = "100";
        row1["Amount"] = "130000";

        DataRow row2 = dt.NewRow();
        row2["ProductName"] = "Gạo dẻo";
        row2["ProductID"] = "1";
        row2["Price"] = "11000";
        row2["Weight"] = "10";
        row2["Amount"] = "110000";
        dt.Rows.Add(row2);
        dt.Rows.Add(row1);

        Session["ShoppingCart"] = dt;
    }
    */
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {
        try
        {
            RadNumericTextBox radNumeric = (RadNumericTextBox)sender;

            string weight = radNumeric.Text;
            if (double.Parse(weight) <= 0)
            {

                radNumeric.Text = "1";
                weight = radNumeric.Text;
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập trọng lượng lớn hơn 0");
                // return;
            }
            //GridDataItem dataItem = (GridDataItem)radNumeric.NamingContainer;
            GridViewRow currentItem = (GridViewRow)radNumeric.NamingContainer;
            Label lblPrice = (Label)currentItem.FindControl("lblPrice");
            string price = lblPrice.Text.Replace(",", "");
            Label lblAmount = (Label)currentItem.FindControl("lblAmount");
            lblAmount.Text = String.Format("{0:#,#.##}", double.Parse(weight) * double.Parse(price));

            decimal? sum = 0;
            int totalWeight = 0;
            foreach (GridViewRow row in gvProduct.Rows)
            {
                Label AmountLabel = (Label)row.FindControl("lblAmount");
                RadNumericTextBox txtQuantity = (RadNumericTextBox)row.FindControl("txtQuantity");
                sum = sum + DecimalOrNull(AmountLabel.Text.Replace(",", ""));

                string isPromotion = row.Cells[5].Text;
                if (isPromotion == "1")
                {
                    totalWeight = totalWeight + int.Parse(txtQuantity.Text.Replace(",", ""));
                }
            }

            sumWeight.InnerText = totalWeight.ToString();
            CalsumHelp(sum, 0, 0);
            DataTable dtPro = loadPromotionPromotion(totalWeight, 0);
            bindingPromotion(dtPro);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-txtQuantity_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    protected void txtQuantitySelect_TextChanged(object sender, EventArgs e)
    {
        try{
        RadNumericTextBox radNumeric = (RadNumericTextBox)sender;
        string QtySelect = radNumeric.Text == "" ? "0" : radNumeric.Text;
        
        GridViewRow currentItem = (GridViewRow)radNumeric.NamingContainer;

        string ProductID = currentItem.Cells[2].Text;

        string Weight = currentItem.Cells[5].Text;
       // string GvPromotionQuantity = currentItem.Cells[3].Text;

        int TotalWeightSelect = Convert.ToInt32(QtySelect) * Convert.ToInt32(Weight);
        int totalWeight = Convert.ToInt32(sumWeight.InnerText);
        if (ViewState["dtPromotion"] != null)
        {
            DataTable dtPro = (DataTable)ViewState["dtPromotion"];

            DataRow[] rowArr = dtPro.Select("ProductID='" + ProductID + "'");
            if (Convert.ToInt32(QtySelect) < 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được nhỏ hơn 0");
                radNumeric.Text = "0";
                DataRow row = rowArr[0];
                row["PromotionQuantitySelect"] = "0";
                return;
            }

            if (rowArr.Count() > 0)
            {
                DataRow row = rowArr[0];
                row["PromotionQuantitySelect"] = QtySelect;
            }
            
            int sumWeightSelected = Convert.ToInt32(dtPro.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"]) * IntOrNull(dr["PromotionQuantitySelect"])));
            int totalWeightRemain = totalWeight - sumWeightSelected;
            if (totalWeightRemain < 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được vượt quá số lượng khuyến mãi");
                radNumeric.Text = "0";
                DataRow row = rowArr[0];
                row["PromotionQuantitySelect"] = "0";
                return;
            }
            int PromotionQuantity = 0;
            foreach (DataRow r in dtPro.Rows)
            {
                PromotionQuantity = totalWeightRemain / Convert.ToInt32(r["Weight"]);
                r["PromotionQuantity"] = PromotionQuantity;
            }
            ViewState["dtPromotion"] = dtPro;
            bindingPromotion(dtPro);
            }
        }
        catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-txtQuantitySelect_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
}